<template>
  <div class="wrapper">
    <Form :label-width="80">
        <FormItem label="颜色" >
            <form-colors @change="handlerChange" v-model="svg.colors"></form-colors>
        </FormItem>
    </Form>
  </div>
</template>

<script>
import { Vue, Component, Watch, Model, Emit} from 'vue-property-decorator'
import {
  State,
  Action,
  Getter
} from 'vuex-class'
import {FormColors} from "../forms"
@Component({
  components: {
    FormColors
  }
})
export default class FormText extends Vue {
  @Getter curElement
  @State curElementId
  @Action actChangeElement
  svg={
    svg: "",
    colors: []
  }
  @Watch('curElementId')
  onCurElementIdChange () {
    if (this.curElement.type === 'svg') {
      this.svg = { ...this.curElement.extra }
      if (!/fill/.test(this.svg.svg)) {
        this.svg.svg = this.svg.svg.replace(/<svg /i, "<svg fill='#000000' ")
      }
      this.svg.colors = this.getColorsFromSvg(this.svg.svg)
    }
  }

  getColorsFromSvg (str) {
    let colors = str.match(/["']#([0-9a-zA-Z]{3}|[0-9a-zA-Z]{6})['"]/g)
    if (!colors) {
      return ["#000"]
    }
    return colors.map(color => color.replace(/['"]/g, ''))
  }

  mounted () {
    if (this.curElement.type === 'svg') {
      this.svg = { ...this.curElement.extra }
      this.onCurElementIdChange()
    }
  }
  handlerChange () {
    let svg = ""
    let svgSplit = this.svg.svg.split(/["']#[0-9a-z]{6}['"]|["']#[0-9a-z]{3}['"]/img)
    for (var i = 0; i < this.svg.colors.length; i++) {
      svg += (svgSplit[i] + (this.svg.colors[i] || "#000000"))
    }
    svg += svgSplit[i]
    this.actChangeElement({
      extra: {svg, colors: this.svg.colors}
    })
  }
}

</script>
<style lang="less" scoped>

</style>
